package com.dongdongshop.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.service.SeckillService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.vo.SeckillGoodsVO;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("seckill")  //继承降级controller
public class SeckillController extends BaseController {

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private JwtUtil jwtUtil;

    //自动更新,定时任务
    //凌晨自动更新,缓存预热
    @XxlJob(value = "catchPreHot")
    public Result catchPreHot() {
        seckillService.catchPreHot();
        System.out.println("测试");
        return Result.OK();
    }

    /**
     * 查询秒杀全部商品
     *
     * @return
     */
    @GetMapping("seckillList")
    @SentinelResource(value = "seckillList", blockHandler = "hotBlockHandler")
    public Result seckillList() {
        List<SeckillGoodsVO> goodsVOS = seckillService.seckillList();
        return Result.OK().setData(goodsVOS);
    }

    /**
     * @param id 秒杀商品id
     * @return
     */
    @GetMapping("seckillGoodsById")
    @SentinelResource(value = "seckillGoodsById", blockHandler = "seckillGoodsById")
    public Result seckillGoodsById(@RequestParam Long id) {
        SeckillGoodsVO goodsVO = seckillService.seckillGoods(id);
        return Result.OK().setData(goodsVO);
    }

    //测试方法
    @GetMapping("getSuperStar")
    @SentinelResource("getSuperStar")
    public Result getSuperStar(String superStar) {
        return Result.OK().setData(superStar);
    }


    /**
     * @param AutharizeToken token
     * @param id             秒杀商品id
     * @return
     */
    @PostMapping("submitOrder")
    public Result submitOrder(@RequestHeader String AutharizeToken, @RequestParam Long id) {
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        if (claims == null) {
            return Result.RESPOSE(ResultEnum.INVALID_TOKEN);
        }
        String userId = claims.getId();
        try {
            seckillService.submitOrder(userId, id);
        } catch (Exception e) {
            return Result.FAIL().setData(e.getMessage());
        }
        return Result.OK();
    }
}
